package 排序算法;

public class selectDemo {
    static int[] arr1 = {3,5,1,-2,9,8};
    static int[] arr2 = {-2,1,3,5,8,9};
    public static void main(String[] args) {
        boolean b = TrueOrFalse();
        if(b){
            Speed();
        }else{
            print(arr1);
        }
    }

    /*
     * 选择排序 时间复杂度O(n^2)
     * */
    private static void SelectSort(int[] arr) {
        // (arr.length - 1) n个元素,最多比较n-1次
        for (int i = 0; i < arr.length - 1; i++) {
            // 最小值和最小值的索引初始化为arr[i]
            int min = arr[i];
            int minIndex = i;
            for (int j = i+1; j < arr.length; j++) {
                if (min > arr[j]) {
                    min = arr[j];
                    minIndex = j;
                }
            }
            // 交换
            if(minIndex != i){
                min = arr[i];
                arr[i] = arr[minIndex];
                arr[minIndex] = min;
            }
        }
    }

    public static boolean TrueOrFalse(){
        SelectSort(arr1);
        for (int i = 0; i < arr1.length; i++) {
            if(arr1[i] != arr2[i]){
                return false;
            }
        }
        return true;
    }
    public static void print(int [] arr){
        for (int j : arr) {
            System.out.print(j + " ");
        }
        System.out.println();
    }
    private static void Speed() {
        int[] arr2 = new int[80000];
        for (int i = 0; i < 80000; i++) {
            arr2[i] = (int)(Math.random()*80000);
        }
        long begin = System.currentTimeMillis();
        SelectSort(arr2);
        long end = System.currentTimeMillis();
        System.out.println((end-begin));
    }

}
